# -*- coding: utf-8 -*-
import paramiko
import os
import datetime
import ConfigParser
config = ConfigParser.RawConfigParser()

ROOT=os.path.dirname(os.path.realpath(__file__))

config.read(os.path.join(ROOT,"../config/server.ini"))

print ROOT,"../config/server.ini"


def run_command(ssh,cmd,comment):
    print comment
    stdin,stdout,stderr = ssh.exec_command(cmd)
    print stdout.readlines()
    print stderr.readlines()


try:
    name = raw_input("请输入要进行安装的服务器代号(具体的参见config目录下的server.ini:")
    print name
    ip=config.get(name,'ip')
    port=config.getint(name,'port')
    username=config.get(name,'user')
    password=config.get(name,'password')



    print '准备开始连接服务器:' + ip,port,username,password
    print 'IP:' + ip
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip,port,username,password)

    tran = paramiko.Transport((ip,port))
    tran.connect(username=username,password=password)
    sftp=paramiko.SFTPClient.from_transport(tran)
    print "连接成功"

    print "上传本地安装脚本"
    sftp.put("installopenresty.sh","/home/installopenresty.sh")

    print "安装ubuntu依赖库,请等待此过程可能会相当漫长"
    s="""
        cd /home
        chmod 777 installopenresty.sh
        sh installopenresty.sh
    """
    stdin,stdout,stderr = ssh.exec_command(s)
    print stdout.readlines()

    print "安装ubuntu依赖库,请等待此过程可能会相当漫长"

    restylib = 'resty.zip'
    print "上传oprenresty的依赖库文件"
    sftp.put(restylib, "/usr/local/openresty/lualib/"+restylib)
    tran.close()

    print "安装openresty依赖库"
    s="""
        cd /usr/local/openresty/lualib/
        mv resty resty_bak
        unzip %s
    """%(restylib)
    stdin,stdout,stderr = ssh.exec_command(s)
    print stdout.readlines()
    print "安装oprenresty依赖库成功"
    ssh.close()
    print '安装完成你可以快乐的跟oprenresty一起玩耍'
except Exception as e:
    print e
    # raise
else:
    pass
finally:
    pass



